package com.loong.life.handler;

import com.alibaba.fastjson.JSONObject;
import com.loong.common.constant.AgentStatus;
import com.loong.common.domain.Pager;
import com.loong.common.exception.GlobalException;
import com.loong.common.executor.BatchExecutor;
import com.loong.common.paasoo.config.PaaSooConfig;
import com.loong.common.paasoo.utils.PaaSooSmsApiUtil;
import com.loong.common.paasoo.utils.PaaSooUtil;
import com.loong.common.utils.Md5Utils;
import com.loong.common.utils.TransformUtils;
import com.loong.life.business.AgentInformationBusiness;
import com.loong.life.common.backend.param.AgentInformationParam;
import com.loong.life.common.backend.param.AgentQueryParam;
import com.loong.life.common.backend.result.AgentInformationResult;
import com.loong.life.common.forehead.param.PhoneNumberForeheadParam;
import com.loong.life.common.forehead.result.AgentAndAgentProductForeheadResult;
import com.loong.life.common.forehead.result.AgentForeheadResult;
import com.loong.life.common.forehead.result.AgentProductForeheadResult;
import com.loong.life.model.AgentInformation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 处理有关代理商信息业务的handler
 * @Author: 刘群
 * @Date: 2020/11/26 16:50
 */
@Slf4j
@Service
public class AgentInformationHandler {


    @Resource
    private AgentInformationBusiness agentBusiness;

    @Resource
    private AgentProductHandler productHandler;

    @Resource
    private BatchExecutor batchExecutor;

    /**
     * 后台新增代理商
     * @param param 代理商参数
     */
    public void saveAgent(AgentInformationParam param){
        param.setCreateTime(new Date());
        //新增的代理商的状态都是未审核
        param.setStatus(AgentStatus.UNAUDITED);
        agentBusiness.save(TransformUtils.transform(param, AgentInformation.class));
    }

    /**
     * 后台更新代理商
     * @param param 代理商参数
     */
    public void updateAgent(AgentInformationParam param){
        param.setLastUpdateTime(new Date());
        agentBusiness.updateByPrimaryKeySelective((TransformUtils.transform(param, AgentInformation.class)));
    }

    /**
     * 后台批量删除代理商
     * @param idList 代理商id集合
     * @return 删除响应的信息
     */
    public void batchDeleteAgent(List<Long> idList) {
        batchExecutor.batchExecute(idList, id -> id.toString(), (item) -> {
            //查询代理商是否正在营业中，若是则不能删除，否则可以直接删除
            //TODO 是否需要考虑删除代理商的同时，将代理商下面的产品也删除
            AgentInformation agent = agentBusiness.findById(item);
            if (ObjectUtils.isNotEmpty(agent) && AgentStatus.OPENING.equals(agent.getStatus())){
                throw new GlobalException("agent is used");
            }else {
                agentBusiness.deleteById(item);
            }
        });
    }

    /**
     * 前台根据代理商id查询代理商
     * @param agentId 代理商id
     * @return 代理商
     */
    public AgentForeheadResult foreheadFindAgentById(Long agentId){
        AgentInformation agentInformation = agentBusiness.findById(agentId);
        if (ObjectUtils.isEmpty(agentInformation)) return null;
        return TransformUtils.transform(agentInformation,AgentForeheadResult.class);
    }

    /**
     * 后台分页查询代理商
     * @param param 查询参数
     * @return 分页结果
     */
    public Pager<AgentInformationResult> pageQueryAgent(AgentQueryParam param){
        Pager<AgentInformation> pager = agentBusiness.pageQuery(param, () -> agentBusiness.findAgentByParam(param));
        return TransformUtils.transformPage(pager,AgentInformationResult.class);
    }

    /**
     * 公共方法：根据代理商名称获取代理商的信息
     * @param agentName 代理商名称
     * @return 代理商
     */
    private AgentForeheadResult commonFindAgentByAgentName(String agentName){
        List<AgentInformation> agentList = agentBusiness.findAgentByAgentName(agentName);
        if (CollectionUtils.isEmpty(agentList)) return null;
        return TransformUtils.transform(agentList.get(0), AgentForeheadResult.class);
    }

    /**
     * 前台根据手机号码查询运营商及运营商的产品
     * @param param 手机号码参数
     * @return 运营商和运营商产品封装的结果
     */
    public AgentAndAgentProductForeheadResult foreheadGetPhoneOperatorAndProducts(PhoneNumberForeheadParam param) {
        //根据手机号码查询出代理商名称
        PaaSooConfig paaSooConfig = PaaSooUtil.getPaaSooConfig();
        //区号
        final String COUNTRY_CODE = "63";
        String validNumber = PaaSooSmsApiUtil.getValidNumber(paaSooConfig.getKey(), paaSooConfig.getSecret(), COUNTRY_CODE, param.getPhoneNumber());
        JSONObject jsonObject = JSONObject.parseObject(validNumber);
        String operator = (String) jsonObject.get("operator");
        //根据代理商名称查询出代理商
        AgentForeheadResult agent = this.commonFindAgentByAgentName(operator);
        //根据代理商id查询代理商产品
        List<AgentProductForeheadResult> productList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(agent)) {
            productList = productHandler.findAgentProductByAgentId(agent.getId());
        }
        //先根据充值类型从小到大排序，再根据优惠价从小到大排序
        productList.sort(Comparator.comparing(AgentProductForeheadResult::getProductType).thenComparing(AgentProductForeheadResult::getDiscountPrice));
        return AgentAndAgentProductForeheadResult.builder()
                .agentResult(agent)
                .agentProductList(productList)
                .build();
    }
}
